package ditch

import (
	"encoding/json"
	"errors"
	"gitee.com/david_xxy/helper/util"
	"gitee.com/yebetter/robot/cli"
	"net/http"
)

// 具体工厂 - 企业微信工厂
// WechatBotFactory 实现了 BotFactory 接口，并用链式设置参数
type WechatBotFactory struct {
	bot *wechatBot
}

// 实例化 具体工厂
func NewWechatBotFactory() *WechatBotFactory {
	return &WechatBotFactory{}
}

// 初始化 具体工厂
func (e *WechatBotFactory) InitFactory(params map[string]string) cli.Bot {
	e.bot = &wechatBot{}
	if v, ok := params["url"]; ok {
		e.bot.WebhookURL = v
	}
	return e.bot
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// 具体产品 - 企业微信机器人
// wechatBot 用于发送企业微信消息
type wechatBot struct {
	WebhookURL string
}

// 响应结构
type wechatBotResponse struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

// SendMessage 实现发送消息的功能
func (e *wechatBot) SendMessage(message string) error {
	// 构造消息体
	bodyMap := map[string]interface{}{
		"msgtype": "text",
		"text": map[string]string{
			"content": message,
		},
	}
	resp, err := util.NewHTTPClient().
		SetParam(bodyMap).
		SetHeader(map[string]string{"Content-Type": "application/json"}).
		SetUrl(e.WebhookURL).
		POST()
	if err != nil {
		return err
	}
	// 检查响应
	if resp.StatusCode != http.StatusOK {
		return errors.New("发送消息失败")
	}
	response := &wechatBotResponse{}
	err4 := json.Unmarshal(resp.Body, &response)
	if err4 != nil {
		return err4
	}
	if response.Errcode != 0 {
		return errors.New(response.Errmsg)
	}
	return nil
}
